<?php
/**
 *
 *
 */
class Yz_File
    extends Yz_Class
{


    /**
     *  the file's path name relative to $relativeDir
     *  @var string
     */
    protected $path;


    /**
     *  @param string $path
     *  @param string|null $relativeDir, default to application's current dir; ignored if path starts from root
     *
     */
    public function __construct($path, $relativeDir=null)
    {
        debug($path);
        assert('is_string($path) and "" !== $path');
        if ($relativeDir)
            assert('is_string($relativeDir)');
        if ('/' === $path[0]) {
            $relativeDir = '';
        } else if (null !== $relativeDir) {
            $relativeDir = YZ_LIB === $relativeDir
                ? YZ_LIB
                : rtrim($relativeDir) . '/';
        } else {
            $relativeDir = './';
        }
        $this->path = $relativeDir . $path;
        return;
    }

    /**
     *
     * @return string|null
     * @throw ? ??
     */
    public function getContents()
    {
        $fullPath = $this->path;
        if (is_file($fullPath) && is_readable($fullPath)) {
            return file_get_contents($fullPath);
        }
        return null;
    }

    /** get the file's extension
     *
     *  @return string
     */
    public function getExtension()
    {
        $name = $this->getName();
        $ext = strrchr($name, '.');
        if (false === $ext) {
            return "";
        } else {
            return substr($ext, 1);
        }
    }

    /** get the file's name
     *
     *  @return string
     */
    public function getName()
    {
        return basename($this->path);
    }

    /**
     *
     * @return int|null
     * @throw ? ??
     */
    public function getSize()
    {
        $fullPath = $this->path;
        if (is_file($fullPath)) {
            return filesize($fullPath);
        }
        return null;
    }

    /**
     *
     * @return string|null
     * @throw ? ??
     */
    public function isFile()
    {
        $fullPath = $this->path;
        if (is_file($fullPath) && is_readable($fullPath)) {
            return true;
        }
        return false;
    }


    /**
     *  TODO return absolute path ???
     *
     */
    public function __toString()
    {
        return $this->path;
    }

}
